using SmartCommunity.WebApi.Services.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace SmartCommunity.WebApi.Controllers.System
{
    /// <summary>
    /// API接口：操作日志
    /// </summary>
    [ApiController]
    [Route("api/system/[controller]")]
    public class LogController : BaseController
    {
        #region 构造函数
        private readonly LogService logService;
        public LogController(LogService logService)
        {
            this.logService = logService;
        }
        #endregion

        #region 查询导出 
        /// <summary>
        /// 分页查询
        /// </summary>
        [HttpGet]
        public async Task<PageResult<LogDto>> GetList([FromQuery] LogQuery query, [FromQuery] Pager pager)
        {
            return await logService.FindPagedList(query, pager, CurrentUser);
        }

        /// <summary>
        /// 通过主键查询
        /// </summary>
        /// <param name="id">主键ID</param>
        [HttpGet("{id}")]
        public async Task<LogDto> GetOne(long id)
        {
            return await logService.FindLogById(id);
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        [HttpGet("export")]
        public async Task<ActionResult> ExportExcel([FromQuery] LogQuery query)
        {
            var pageData = await logService.FindPagedList(query, Pager.Unpaged, CurrentUser);
            var exporter = new ExcelExporter();
            exporter.AddTitleRow(0, "操作类型", "日志类别(简短描述)", "日志内容", "请求URL", "请求方式", "请求参数", "是否执行成功", "执行时长,毫秒", "客户端IP", "客户端操作系统", "客户端浏览器", "操作人", "操作时间");
            int rowIndex = 1;
            foreach (var dto in pageData.DataList)
            {
                exporter.AddDataRow(rowIndex++, 0, dto.OperateType, dto.LogTitle, dto.LogContent, dto.RequestPath, dto.RequestMethod, dto.RequestParam, dto.Success, dto.ExecuteTime, dto.ClientIp, dto.ClientOs, dto.ClientBrowser, dto.CreatedBy, dto.CreatedTime);
            }
            var bytes = exporter.GetExcelData();
            return File(bytes, CONTENT_TYPE_EXCEL, $"操作日志导出{DateTime.Now:yyyyMMddHHmmss}.xlsx");
        }
        #endregion

        #region 删除日志
        /// <summary>
        /// 删除操作日志
        /// </summary>
        [HttpDelete]
        [Log("删除操作日志", OperateType.Delete)]
        public async Task<IActionResult> DeleteLog([FromQuery] long[] ids)
        {
            await logService.DeleteByIds(ids, CurrentUser);
            return NoContent();
        }

        /// <summary>
        /// 删除操作日志
        /// </summary>
        [Authorize(Roles = AppConstants.SUPER_ADMIN)]
        [HttpDelete("clear")]
        [Log("清除操作日志", OperateType.Delete)]
        public async Task<IActionResult> DeleteLog([FromQuery] LogQuery query)
        {
            await logService.ClearLogs(query);
            return NoContent();
        }
        #endregion
    }
}
